package com.je.thrid.util;

import com.je.core.util.bean.DynaBean;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DateSourceUtil {

    /**
     * 获取数据库中所有的表名称
     *
     * @param conn
     *            数据库的连接
     * @return 该数据库中所有的表名称
     * @throws SQLException
     */
    public static List<DynaBean> getTables(Connection conn,String schemaPattern) throws SQLException {
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet resultSet = metaData.getTables(conn.getCatalog(), schemaPattern, null, new String[] {"TABLE"});
        List<DynaBean> tables = new ArrayList<>();
        while (resultSet.next()) {
            String tableName = resultSet.getString("TABLE_NAME");
            DynaBean dynaBean = new DynaBean();
            dynaBean.setStr("tableName",  resultSet.getString("REMARKS"));
            dynaBean.setStr("tableCode", tableName);
            tables.add(dynaBean);
        }
        return tables;
    }

    /**
     * 获取指定表的所有字段名称
     *
     * @param conn
     *            数据库连接
     * @param tableName
     *            表名称
     * @return 该表所有的字段名称
     * @throws SQLException
     */
    public static List<String> getColumns(Connection conn, String tableName) throws SQLException {
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet rs = metaData.getColumns(conn.getCatalog(), null, tableName, null);
        List<String> columns = new ArrayList<>();
        while (rs.next()) {
            String name = rs.getString("COLUMN_NAME");
            columns.add(name);
        }
        return columns;
    }
}
